package ext.tianma.bom.workflow;

import java.util.ArrayList;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import ext.tianma.version.ComToolUtil;

public class WTPartToolUtil {
	
	
	private WTPartToolUtil(){
		
	}
		
	
	/** YW
	 * 通过WTPartMaster对象获取最新部件 
	 * @param master WTPartMaster对象
	 * @return WTPart  最新的部件对象
	 * @throws WTException
	 */
	public static WTPart getLatestWTPartByMaster(WTPartMaster master)  throws WTException  {
		if(ComToolUtil.isEmpty(master))
			return null;
		
        Iterated iterated = null;
        QueryResult qr = VersionControlHelper.service.allIterationsOf(master);
        while(qr.hasMoreElements()){
        	Object obj = qr.nextElement();
        	if(obj != null && obj instanceof Iterated){
	            iterated = (Iterated)obj;
	            if(iterated.isLatestIteration())
	            	break;
        	}
        }
        
        return (WTPart)iterated;
	}
	
	
	/**YW
	 * 通过【部件编号】获取最新部件
	 * 通过测试：一个编号只会返回一个与之对应的Master
	 * @param partNumber 部件编号
	 * @return WTPart
	 * @throws WTException
	 */
	public static WTPart getLatestWTPartByNumber(String partNumber) throws WTException {
		if(ComToolUtil.isEmpty(partNumber))
    		return null;		
		ArrayList<WTPartMaster> masters = getWTPartMasterByNumber(partNumber);		
		//通过测试：一个编号只会返回一个与之对应的Master		
		return getLatestWTPartByMaster(masters.get(0));
	}
	
	    
    /**YW
     * 通过【部件编号】获得所有WTPartMaster对象
     * 通过测试：一个编号只会返回一个与之对应的Master
     * @param partNumber 部件编号
     * @return ArrayList<WTPartMaster>
     * @throws WTException
     */
    @SuppressWarnings("deprecation")
	public static ArrayList<WTPartMaster> getWTPartMasterByNumber(String partNumber) throws WTException {
	       
    	if(ComToolUtil.isEmpty(partNumber))
    		return null;
    	
        QuerySpec qs = new QuerySpec(WTPartMaster.class);
        SearchCondition sc = new SearchCondition(WTPartMaster.class, "number", "=", partNumber);
        qs.appendSearchCondition(sc);
        QueryResult qr = PersistenceHelper.manager.find(qs);
        
        ArrayList<WTPartMaster> result = new ArrayList<WTPartMaster>();
        
        if(qr.hasMoreElements()){        	
            Object obj = qr.nextElement();
            if(!ComToolUtil.isEmpty(obj)&&obj instanceof WTPartMaster)
            	result.add((WTPartMaster)obj);
        }
        
        return result;
   }
	
	
}